import React, { Component } from "react";
import {Button, Popconfirm, Radio, Row, Table, Modal, Checkbox, Tooltip, Icon} from "antd";
import { connect } from "dva";
import { openNotificationWithIcon } from "utils/comm";
import { typeOptions } from "components/flowdetailpannel/FlowParameters";
import TransactorSelect from "./TransactorSelect";
import FlowParamsSelector from "./FlowParamsSelector";
// import FlowRelationSelector from "./FlowRelationSelector";
import styles from "./UserTaskSelector.less";

const RadioGroup = Radio.Group;
// const CheckboxGroup = Checkbox.Group;

const typeLabelMap = { STA: "人员", ORG: "组织", ROL: "角色", GROUP: '用户组', POSITION: '岗位', RELATIONSHIP: '关系', FUNCTION: '自定义函数' };
const tabKeyValueMap = { 1: "STA", 2: "VAR", 3: "INIT", 9:"EMPTY" };

const RelationStandardMap = {
  NONE: "无",
  ASSIGNEE: "办理人",
  INITIATOR: "流动启动人",
};
const RelationNodeMap = {
  NONE: "无",
  PREVIOUS: "上一节点",
  SPECIFY: "指定节点",
};
const RelationRelationMap = {
  NONE: "无",
  DEPARTMENT_STAFF: "同部门人员",
  DEPARTMENT_LEADER: "同部门领导",
  SUPERIOR_DEPARTMENT_STAFF: "上级部门人员",
  SUPERIOR_DEPARTMENT_LEADER: "上级部门领导",
};

@connect(({ FlowChart }) => ({
  // 在src/components/flowdetailpannel/NodeSelected.jsx加载数据
  noticeTypeData: FlowChart.noticeTypeData,
}))
class UserTaskSelectorRadio extends Component {
  relationColumns = [
    {
      title: "节点",
      dataIndex: "node",
      render: (text, record) =>
        record.node === "SPECIFY"
          ? record.selectNodeName
          : RelationNodeMap[text],
    },
    {
      title: "基准",
      dataIndex: "benchmark",
      render: text => RelationStandardMap[text],
    },
    {
      title: "关系",
      dataIndex: "relation",
      render: text => RelationRelationMap[text],
    },
  ];

  constructor(props) {
    super(props);
    const { noticeTypeData } = props;
    this.setupNoticeTypeMap(noticeTypeData || []);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.state = {
      activeKey: "1",
      candidateUsersVisible: false,
      selectedSTAKeys: [],
      selectedVARKeys: [],
      visible: false,
      // relationPopVisible: false,
    };
  }

  componentDidMount() {
    const { selectedModel = {} } = this.props;
    this.initActiveKey(selectedModel);
  }

  setupNoticeTypeMap = datas => {
    if (!this.noticeMap && datas.length > 0) {
      this.noticeMap = datas.reduce((map, data) => {
        map[data.code] = data;
        return map;
      }, {});
    }
  };

  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { selectedModel } = this.props;
    const { noticeTypeData = [] } = nextProps;
    this.setupNoticeTypeMap(noticeTypeData);

    if ((nextProps.selectedModel || {}).id !== selectedModel.id) {
      this.initActiveKey(nextProps.selectedModel);
      this.setState({
        // eslint-disable-line
        selectedSTAKeys: [],
        selectedVARKeys: [],
      });
    }
  }

  initActiveKey = selectedModel => {
    const { properties = {} } = (selectedModel || {}).model || {};
    const { candidateUsers = [], candidateSetNull } = properties;
    const userSelectValue = this.getUserSelectValue(candidateUsers);
    let activeKey = "1";
    if (userSelectValue === "VAR") {
      activeKey = "2";
    }
    if (candidateSetNull && candidateSetNull === "1") {
      activeKey = "9";
    }

    this.setState({ activeKey });
  };

  getUserSelectValue = candidateUsers => {
    if (candidateUsers.length === 0) {
      if (this.userSelectValue === "STA" || this.userSelectValue === "VAR") {
        return this.userSelectValue;
      }
      this.userSelectValue = "None";
      return "None";
    } else if (candidateUsers.some(ele => ele.type === "INIT")) {
      // this.hqdisable = true;
      this.userSelectValue = "INIT";
      return "INIT";
    } else if (candidateUsers.some(ele => ele.type === "VAR")) {
      // this.hqdisable = true;
      this.userSelectValue = "VAR";
      return "VAR";
    } else {
      this.userSelectValue = "STA";
      return "STA";
    }
  };

  onTab = e => {
    const { value: key } = e.target;
    const { selectedModel = {} } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    const { candidateUsers = [], relativeRelations = [] } = properties;
    let checkValue = [];

    const variableDataSource = candidateUsers.map(item => {
      const { name, code, varType, type } = item;
      if (type && type === "INIT") {
        checkValue = ["INIT"];
      }
      return { name, code, type: varType };
    });
    if (
      (candidateUsers.length > 0 && candidateUsers[0].name !== "") ||
      (variableDataSource.length > 0 && variableDataSource[0].name !== "") ||
      (relativeRelations.length > 0 && relativeRelations[0].name !== "") ||
      checkValue.length > 0
    ) {
      Modal.warning({
        title: "切换办理人设置方式提醒",
        content: (
          <div>
            <p>清空当前办理人设置记录后，才能切换到</p>
            <p>其他办理人设置方式</p>
          </div>
        ),
        onOk: () => {},
        okText: "知道了",
      });
    } else {
      this.onTabChange(key);
    }
  };

  onTabChange = key => {
    const { disable } = this.props;
    if (disable) {
      return;
    }

    this.setState({ activeKey: key });

    const value = tabKeyValueMap[key];
    const {
      changeModelVariableRef,
      handleChangeProperties,
      selectedModel = {},
    } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    const { candidateUsers = [] } = properties;
    // let changeValue = [];
    this.userSelectValue = value;
    if (value === "None") {
      // 以前还有'请选择'选项，value为'None'
      if (properties.multiinstance_type !== "None") {
        handleChangeProperties(
          "multiinstance_type",
          "None",
          selectedModel.model,
          selectedModel.shape,
          false,
        );
      }
    } else if (value === "STA") {
      this.setState({ selectedSTAKeys: [] });
    } else if (value === "VAR") {
      this.setState({ selectedVARKeys: [] });
    }

    if (value === "EMPTY") {
      handleChangeProperties(
        "candidateSetNull",
        "1",
        selectedModel.model,
        selectedModel.shape,
        false,
      );
    } else {
      handleChangeProperties(
        "candidateSetNull",
        "0",
        selectedModel.model,
        selectedModel.shape,
        false,
      );
    }
    // handleUsersSelect(changeValue, noticeTypeData[0]);
    const codes = candidateUsers.filter(v => v.type === "VAR").map(v => v.code);
    changeModelVariableRef(codes, selectedModel, false);
  };

  handleCheckChange = v => {
    const {
      handleChangeProperties,
      handleUsersSelect,
      noticeTypeData,
      selectedModel = {},
    } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    // console.log(properties);
    // if (properties.multiinstance_type === "Parallel") {
    //   this.openNotificationWithIcon(
    //     "warning",
    //     "",
    //     "已设置会签任务，不可选择办理人设置中的相对关系—流程发起人",
    //   );
    //   return;
    // }
    let changeValue = [];
    if (v.includes("BOSS")) {
      this.openNotificationWithIcon("warning", "", "暂未实现，需4A平台支持");
    } else if (v.includes("INIT")) {
      changeValue = [{ name: "", type: "INIT", code: "" }];
      if (properties.multiinstance_type !== "None") {
        handleChangeProperties(
          "multiinstance_type",
          "None",
          selectedModel.model,
          selectedModel.shape,
          false,
        );
      }
    }
    handleUsersSelect(changeValue, noticeTypeData[0]);
  };

  handleVarVisible = visible => {
    this.setState({ visible });
  };

  handleUserVisible = v => {
    this.setState({ candidateUsersVisible: v });
  };

  /*
  handleRelationVisible = visible => {
    this.setState({
      relationPopVisible: visible,
    });
  };
  */

  renderButtons = (type, candidateUsers) => {
    const {
      selectedSTAKeys = [],
      selectedVARKeys = [],
      selectedRELKeys = [],
    } = this.state;
    const {
      changeModelVariableRef,
      disable,
      handleDeleteUsers,
      handleDeleteRelation,
      selectedModel = {},
    } = this.props;
    let onAdd = this.handleVarVisible;
    let suffix = "变量";
    let keys = selectedVARKeys;
    if (type === "STA") {
      onAdd = this.handleUserVisible;
      suffix = "人员";
      keys = selectedSTAKeys;
    }
    if (type === "REL") {
      onAdd = this.handleRelationVisible;
      suffix = "关系";
      keys = selectedRELKeys;
    }
    return (
      <Row
        className={styles.buttons}
        justify="space-between"
        style={{ marginTop: 16 }}
        type="flex"
      >
        <Button disabled={disable} onClick={() => onAdd(true)}>
          添加
        </Button>
        {!disable && keys.length > 0 ? (
          <Popconfirm
            placement="top"
            title={`请确认是否删除当前选中${suffix}`}
            onConfirm={() => {
              this.setState(
                {
                  selectedSTAKeys: [],
                  selectedVARKeys: [],
                  selectedRELKeys: [],
                },
                () => {
                  if (type === "VAR") {
                    changeModelVariableRef(keys, selectedModel, false);
                  }
                  if (type === "REL") {
                    handleDeleteRelation(candidateUsers, false, keys);
                  }
                  handleDeleteUsers(candidateUsers, false, keys);
                  this.forceUpdate();
                },
              );
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>删除</Button>
          </Popconfirm>
        ) : (
          <Button disabled>删除</Button>
        )}
        {!disable && candidateUsers.length > 0 ? (
          <Popconfirm
            placement="top"
            title={`请确认是否删除所有${suffix}`}
            onConfirm={() => {
              this.setState(
                {
                  selectedSTAKeys: [],
                  selectedVARKeys: [],
                  selectedRELKeys: [],
                },
                () => {
                  const codes = candidateUsers.map(({ code }) => code);
                  if (type === "VAR") {
                    changeModelVariableRef(codes, selectedModel, false);
                  }
                  if (type === "REL") {
                    handleDeleteRelation(candidateUsers, true);
                  }
                  handleDeleteUsers(candidateUsers, true);
                  this.forceUpdate();
                },
              );
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>全删</Button>
          </Popconfirm>
        ) : (
          <Button disabled>全删</Button>
        )}
      </Row>
    );
  };

  onAddVariables = (addedRows, rows, selectedModel) => {
    const {
      changeModelVariableRef,
      handleUsersSelect,
      noticeTypeData,
    } = this.props;
    const codes = addedRows.map(({ code }) => code);
    changeModelVariableRef(codes, selectedModel, true);
    const selectedRows = addedRows.concat(rows);
    const selectData = selectedRows.map(({ name, code, type, varType }) => ({
      name,
      code,
      type: "VAR",
      varType: varType ?? type,
    }));
    handleUsersSelect(selectData, noticeTypeData[0]);
    this.setState({ visible: false });
  };

  // 添加相对关系
  onAddRelation = (param, rows) => {
    const { handleRelationSelect } = this.props;
    const selectedRows = [param].concat(rows);
    handleRelationSelect(selectedRows);
    this.handleRelationVisible(false);
  };

  // handleCheckbox=(e) => {
  //   console.log(`checked = ${e.target.checked}`, e.target.value);
  // }

  render() {
    const {
      activeKey,
      candidateUsersVisible,
      selectedSTAKeys = [],
      selectedVARKeys = [],
      // selectedRELKeys = [],
      visible,
      // relationPopVisible,
    } = this.state;
    const {
      appId,
      disable,
      dispatch,
      handleUsersSelect,
      modelVariables = [],
      noticeTypeData,
      selectedModel = {},
      // stackRadios = false,
    } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    const {
      candidateUsers = [],
      // noticeChannel = [],
      // relativeRelations = [],
    } = properties;

    // let checkValue = [];

    const variableDataSource = candidateUsers.map(item => {
      const { name, code, varType } = item;
      /*
      const { name, code, varType, type } = item;
      if (type && type === "INIT") {
        checkValue = ["INIT"];
      }
      */
      return { name, code, type: varType };
    });
    const selectedVariablesMap = candidateUsers.reduce((map, { code }) => {
      map[code] = true;
      return map;
    }, {});
    const otherVariables = modelVariables
      .filter(v => ["STA", "ORG", "ROL", "GROUP", "POSITION", "RELATIONSHIP", "FUNCTION"].indexOf(v.type) > -1)
      .filter(v => !selectedVariablesMap[v.code]);
    return (
      <>
        <RadioGroup
          value={activeKey}
          className={`${styles.root} ${disable ? styles.disabled : ""}`}
          onChange={this.onTab}
          size="small"
        >
          <Radio value="1">从组织库中选择</Radio>
          {activeKey === "1" && (
            <div style={{ padding: "0 8px" }}>
              <Table
                // style={{ marginTop: 18 }}
                columns={[
                  { title: "名称", dataIndex: "name" },
                  {
                    title: "类型",
                    dataIndex: "type",
                    render: v => {
                      return typeLabelMap[v];
                    },
                  },
                ]}
                dataSource={candidateUsers}
                pagination={{
                  pageSize: 5,
                }}
                rowKey="code"
                rowSelection={{
                  fixed: true,
                  getCheckboxProps: () => ({
                    disabled: disable,
                  }),
                  onChange: keys => {
                    if (disable) return;
                    this.setState({ selectedSTAKeys: keys });
                  },
                  selectedRowKeys: selectedSTAKeys,
                }}
                size="small"
              />
              {this.renderButtons("STA", candidateUsers)}
            </div>
          )}
          <Radio value="2">从变量中获取</Radio>
          {activeKey === "2" && (
            <div style={{ padding: "0 8px" }}>
              <Table
                columns={[
                  {
                    title: "名称",
                    dataIndex: "name",
                    ellipsis: true,
                    render: v => (
                      <span className={styles.shortCell} title={v}>
                        {v}
                      </span>
                    ),
                  },
                  {
                    title: "编码",
                    dataIndex: "code",
                    ellipsis: true,
                    render: v => (
                      <span className={styles.shortCell} title={v}>
                        {v}
                      </span>
                    ),
                  },
                  {
                    title: "类型",
                    dataIndex: "type",
                    ellipsis: true,
                    render: v => {
                      const typeOption = typeOptions.filter(
                        o => o.value === v,
                      )[0] || { label: "" };
                      return typeOption.label;
                    },
                  },
                  // {
                  //   title: "类型",
                  //   dataIndex: "type",
                  //   render: (text, record) => (<Checkbox onChange={this.handleCheckbox} checked={record.AUTHORITY_ALL} value={record.ID} />),
                  // }
                ]}
                dataSource={variableDataSource}
                pagination={{
                  pageSize: 5,
                }}
                rowKey="code"
                rowSelection={{
                  fixed: true,
                  getCheckboxProps: () => ({ disabled: disable }),
                  onChange: selected => {
                    if (disable) return;
                    this.setState({ selectedVARKeys: selected });
                    // this.onNoticeTypeChange(noticetype, candidateUsers, variableDataSource);
                  },
                  selectedRowKeys: selectedVARKeys,
                }}
                size="small"
              />
              {this.renderButtons("VAR", candidateUsers)}
            </div>
          )}
          <Radio value="9">留空</Radio>
          <div>
            <Tooltip placement="topRight" title="【留空】：暂不设置处理人，在前序节点手动指定">
              <Icon
                style={{cursor: "pointer"}}
                theme="filled"
                type="question-circle"
              />
            </Tooltip>
          </div>
          {/*
          <Radio value="3">相对关系</Radio>
          {activeKey === "3" && (
            <div style={{ padding: "0 8px" }} className={styles.Checkbox}>
              <CheckboxGroup
                value={checkValue}
                onChange={this.handleCheckChange}
              >
                <Checkbox value="INIT">流程发起人</Checkbox>
                <Checkbox value="BOSS">流程发起人 &gt; 直属领导</Checkbox>
              </CheckboxGroup>
            </div>
          )}
          */}
        </RadioGroup>
        {/* <Tabs
          activeKey={activeKey}
          className={`${styles.root} ${disable ? styles.disabled : ""}`}
          onChange={this.onTab}
          size="small"
        >
          <TabPane
            tab={
              <>
                从组织库中选择
                {activeKey === "1" && candidateUsers.length > 0 && (
                  <Icon type="check" />
                )}
              </>
            }
            key="1"
          />
          <TabPane
            tab={
              <>
                从变量中获取
                {activeKey === "2" && variableDataSource.length > 0 && (
                  <Icon type="check" />
                )}
              </>
            }
            key="2"
          />
          <TabPane
            tab={
              <>
                相对关系
                {activeKey === "3" && relativeRelations.length > 0 && (
                  <Icon type="check" />
                )}
              </>
            }
            key="3"
          />
        </Tabs> */}
        <TransactorSelect
          appId={appId}
          dispatch={dispatch}
          visible={candidateUsersVisible}
          selectData={candidateUsers}
          onCancel={() => this.handleUserVisible(false)}
          userSelect={data => {
            handleUsersSelect(data, noticeTypeData[0]);
            this.handleUserVisible(false);
          }}
          wrapClassName={styles.user_modal}
        />
        <FlowParamsSelector
          value={otherVariables}
          visible={visible}
          onOk={rows =>
            this.onAddVariables(rows, candidateUsers, selectedModel)
          }
          onCancel={() => this.handleVarVisible(false)}
        />
        {/*
        <FlowRelationSelector
          value={otherVariables}
          visible={relationPopVisible}
          onOk={param => this.onAddRelation(param, relativeRelations)}
          onCancel={() => this.handleRelationVisible(false)}
        />
        */}
      </>
    );
  }
}

export default UserTaskSelectorRadio;
